package www.dianbaozu.com.ui.chat.addFriend

import android.view.View
import androidx.fragment.app.viewModels
import com.netease.nim.uikit.api.NIMHelper
import com.netease.nimlib.sdk.RequestCallbackWrapper
import com.netease.nimlib.sdk.ResponseCode
import dagger.hilt.android.AndroidEntryPoint
import www.dianbaozu.com.R
import www.dianbaozu.com.databinding.FragmentAddFriendBinding
import www.wen.com.common.lib.base.fragment.BaseLoadingFragment
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.extension.banEnterKey
import www.wen.com.common.lib.extension.getString
import www.wen.com.common.lib.extension.toast
import www.wen.com.common.lib.extension.trimProxy
import www.wen.com.common.lib.helper.loading.TitleBarUniversalAdapter
import java.util.*

/**
 * @author WEN
 * @Description:添加朋友
 * @date 2020//25 17:48
 */
@AndroidEntryPoint
class AddFriendFragment : BaseLoadingFragment<FragmentAddFriendBinding>(), View.OnClickListener {

    private val addFriendViewModel: AddFriendViewModel by viewModels()

    override val viewModel: BaseViewModel
        get() = addFriendViewModel

    override fun isEnableLoadingHelper(): Boolean = true

    override fun getTitleBarUniversalAdapter(): TitleBarUniversalAdapter =
        TitleBarUniversalAdapter(requireActivity(), "发送好友申请", action = ::titleAction)

    override fun getLayoutId(): Int = R.layout.fragment_add_friend

    override fun lazyInitView() {
        dataBinding.apply {
            listener = this@AddFriendFragment
            viewModel = addFriendViewModel
            etNickName.banEnterKey()
        }
    }

    override fun onClick(v: View) {
        val nickName = dataBinding.etNickName.trimProxy()
        if (nickName.isEmpty()) {
            toast("昵称不能为空")
            return
        }
        addFriendViewModel.searchUserByNickName(nickName) {
            if (it.data == null) {
                toast(getString(R.string.not_exist_user))
                return@searchUserByNickName
            }
            if (it.data.accId == NIMHelper.getUserAccount()){
                toast(getString(R.string.can_not_add_self))
                return@searchUserByNickName
            }
            NIMHelper.addFriend(it.data.accId, callback = object :
                RequestCallbackWrapper<Void?>() {
                override fun onResult(
                    code: Int,
                    result: Void?,
                    exception: Throwable?
                ) {
                    if (code != ResponseCode.RES_SUCCESS.toInt() || exception != null) {
                        toast(getString(R.string.add_failed))
                        return
                    }
                    toast(getString(R.string.com_send_success))
                }
            })
        }
    }

}



